package com.wfs.suanfa.nio.demo.echo.nonio;

import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class PlainNioServer {
    @SneakyThrows
    public static void server(int port){
        ServerSocketChannel socketChannel=ServerSocketChannel.open();
        socketChannel.configureBlocking(false);
        ServerSocket ssocket=socketChannel.socket();
        InetSocketAddress address=new InetSocketAddress(port);
        ssocket.bind(address);
        Selector selector=Selector.open();
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        ByteBuffer mesg = ByteBuffer.wrap("Hi\t\n".getBytes(StandardCharsets.UTF_8));
        for (;;){
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, mesg.duplicate());
                    System.out.println("Accepted connection from " + client);
                }
                 if (key.isWritable()){
                     SocketChannel channel = (SocketChannel)key.channel();
                     ByteBuffer buffer = (ByteBuffer)key.attachment();
                        while (buffer.hasRemaining()){
                            if (channel.write(buffer)==0){
                                break;
                            }
                        }
                        channel.close();
                    }

                }

            }
    }

    public static void main(String[] args) {
        server(7001);
    }
}
